/**
 * 灵感库状态管理
 */
import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import type { InspirationItem, InspirationType } from '@/types/brainstorm';
import { inspirationAIService } from '@/services/inspiration-ai.service';
import { message } from 'antd';

interface InspirationState {
  // State
  items: InspirationItem[];
  tags: string[];
  loading: boolean;
  error: string | null;
  aiEnhancing: boolean;

  // Actions
  loadItems: (filters?: { type?: InspirationType; tags?: string[] }) => Promise<void>;
  addItem: (item: Omit<InspirationItem, 'id' | 'createdAt' | 'updatedAt'>) => Promise<string>;
  updateItem: (itemId: string, updates: Partial<InspirationItem>) => Promise<void>;
  deleteItem: (itemId: string) => Promise<void>;
  searchItems: (query: string) => InspirationItem[];

  // AI增强功能
  aiClassifyItem: (itemId: string) => Promise<void>;
  aiGenerateSummary: (itemId: string) => Promise<void>;
  getRecommendations: (itemId: string, limit?: number) => Promise<InspirationItem[]>;
  batchAIEnhance: (itemIds: string[]) => Promise<void>;
  checkDuplicates: (itemId: string) => Promise<InspirationItem[]>;

  // 灵感捕获
  addFromHotRadar: (hotItem: any) => Promise<string>;
  addFromConversation: (message: any) => Promise<string>;
  addQuickNote: (content: string, tags?: string[]) => Promise<string>;

  loadTags: () => Promise<void>;
  reset: () => void;
}

const initialState = {
  items: [],
  tags: [],
  loading: false,
  error: null,
  aiEnhancing: false,
};

export const useInspirationStore = create<InspirationState>()(
  devtools(
    persist(
      (set, get) => ({
        ...initialState,

        loadItems: async (filters) => {
          set({ loading: true, error: null });
          try {
            // TODO: 调用API加载灵感素材
            console.log('Loading inspiration items with filters:', filters);
            set({ loading: false });
          } catch (error) {
            set({ error: '加载灵感素材失败', loading: false });
          }
        },

        addItem: async (item) => {
          set({ loading: true, error: null });
          try {
            const newItem: InspirationItem = {
              ...item,
              id: `inspiration-${Date.now()}`,
              createdAt: new Date().toISOString(),
              updatedAt: new Date().toISOString(),
            };

            set((state) => ({
              items: [newItem, ...state.items],
              loading: false,
            }));

            return newItem.id;
          } catch (error) {
            set({ error: '添加灵感素材失败', loading: false });
            throw error;
          }
        },

        updateItem: async (itemId, updates) => {
          set({ loading: true, error: null });
          try {
            set((state) => ({
              items: state.items.map((item) =>
                item.id === itemId
                  ? { ...item, ...updates, updatedAt: new Date().toISOString() }
                  : item
              ),
              loading: false,
            }));
          } catch (error) {
            set({ error: '更新灵感素材失败', loading: false });
          }
        },

        deleteItem: async (itemId) => {
          set({ loading: true, error: null });
          try {
            set((state) => ({
              items: state.items.filter((item) => item.id !== itemId),
              loading: false,
            }));
          } catch (error) {
            set({ error: '删除灵感素材失败', loading: false });
          }
        },

        searchItems: (query) => {
          const state = get();
          const lowerQuery = query.toLowerCase();

          return state.items.filter(
            (item) =>
              item.title.toLowerCase().includes(lowerQuery) ||
              item.content.toLowerCase().includes(lowerQuery) ||
              item.tags.some((tag) => tag.toLowerCase().includes(lowerQuery))
          );
        },

        loadTags: async () => {
          try {
            // 从items中提取所有标签
            const state = get();
            const allTags = new Set<string>();

            state.items.forEach((item) => {
              item.tags.forEach((tag) => allTags.add(tag));
            });

            set({ tags: Array.from(allTags).sort() });
          } catch (error) {
            console.error('Failed to load tags:', error);
          }
        },

        // ========== AI增强功能 ==========

        /**
         * AI自动分类素材
         */
        aiClassifyItem: async (itemId: string) => {
          const item = get().items.find(i => i.id === itemId);
          if (!item) {
            message.error('素材不存在');
            return;
          }

          set({ aiEnhancing: true });
          try {
            const result = await inspirationAIService.classifyInspiration(item);

            // 更新素材信息
            await get().updateItem(itemId, {
              tags: [...new Set([...item.tags, ...result.suggestedTags])],
              // 可以添加额外的元数据字段存储分析结果
            });

            // 重新加载标签
            await get().loadTags();

            message.success(`已为"${item.title}"添加${result.suggestedTags.length}个建议标签`);
          } catch (error) {
            console.error('AI分类失败:', error);
            message.error('AI分类失败');
          } finally {
            set({ aiEnhancing: false });
          }
        },

        /**
         * AI生成摘要
         */
        aiGenerateSummary: async (itemId: string) => {
          const item = get().items.find(i => i.id === itemId);
          if (!item) {
            message.error('素材不存在');
            return;
          }

          set({ aiEnhancing: true });
          try {
            const summary = await inspirationAIService.generateSummary(item.content, 100);

            // 更新素材（可以添加summary字段到类型定义中）
            message.success('摘要已生成');
            message.info(summary, 10);
          } catch (error) {
            console.error('生成摘要失败:', error);
            message.error('生成摘要失败');
          } finally {
            set({ aiEnhancing: false });
          }
        },

        /**
         * 获取相关推荐
         */
        getRecommendations: async (itemId: string, limit = 5) => {
          const item = get().items.find(i => i.id === itemId);
          if (!item) {
            return [];
          }

          try {
            const result = await inspirationAIService.getRecommendations(
              item,
              get().items,
              limit
            );
            return result.recommendations;
          } catch (error) {
            console.error('获取推荐失败:', error);
            return [];
          }
        },

        /**
         * 批量AI增强
         */
        batchAIEnhance: async (itemIds: string[]) => {
          const items = get().items.filter(i => itemIds.includes(i.id));
          if (items.length === 0) {
            return;
          }

          set({ aiEnhancing: true });
          message.loading(`正在增强${items.length}个素材...`, 0);

          try {
            const results = await inspirationAIService.batchEnhance(items);

            // 批量更新素材
            for (const [itemId, result] of results.entries()) {
              const item = get().items.find(i => i.id === itemId);
              if (item) {
                await get().updateItem(itemId, {
                  tags: [...new Set([...item.tags, ...result.suggestedTags])],
                });
              }
            }

            // 重新加载标签
            await get().loadTags();

            message.destroy();
            message.success(`成功增强${items.length}个素材`);
          } catch (error) {
            console.error('批量增强失败:', error);
            message.destroy();
            message.error('批量增强失败');
          } finally {
            set({ aiEnhancing: false });
          }
        },

        /**
         * 检查重复素材
         */
        checkDuplicates: async (itemId: string) => {
          const item = get().items.find(i => i.id === itemId);
          if (!item) {
            return [];
          }

          try {
            const result = await inspirationAIService.detectDuplicates(
              item,
              get().items
            );

            if (result.isDuplicate) {
              message.warning(`发现${result.similarItems.length}个相似素材`);
            }

            return result.similarItems;
          } catch (error) {
            console.error('检查重复失败:', error);
            return [];
          }
        },

        // ========== 灵感捕获功能 ==========

        /**
         * 从热点雷达添加素材
         */
        addFromHotRadar: async (hotItem: any) => {
          try {
            const newItem: Omit<InspirationItem, 'id' | 'createdAt' | 'updatedAt'> = {
              title: hotItem.title || hotItem.name || '未命名热点',
              content: hotItem.description || hotItem.content || hotItem.summary || '',
              type: 'link',
              tags: [
                '热点',
                hotItem.platform || '未知平台',
                ...(hotItem.tags || [])
              ],
              source: {
                url: hotItem.url || hotItem.link || '',
                title: hotItem.title || '',
                author: hotItem.author || '',
                platform: hotItem.platform || ''
              }
            };

            const itemId = await get().addItem(newItem);

            // 自动进行AI增强
            if (itemId) {
              setTimeout(() => {
                get().aiClassifyItem(itemId).catch(err => {
                  console.warn('自动分类失败:', err);
                });
              }, 500);
            }

            message.success('已从热点雷达添加到灵感库');
            return itemId;
          } catch (error) {
            console.error('从热点雷达添加失败:', error);
            message.error('添加失败');
            throw error;
          }
        },

        /**
         * 从对话历史添加素材
         */
        addFromConversation: async (conversationMessage: any) => {
          try {
            const newItem: Omit<InspirationItem, 'id' | 'createdAt' | 'updatedAt'> = {
              title: `对话片段 - ${new Date().toLocaleString()}`,
              content: conversationMessage.content || '',
              type: 'text',
              tags: [
                '对话',
                conversationMessage.role === 'assistant' ? 'AI回复' : '用户提问',
                ...(conversationMessage.tags || [])
              ],
              source: {
                url: '',
                title: `对话ID: ${conversationMessage.conversationId || ''}`,
                author: conversationMessage.role === 'assistant' ? 'AI助手' : '用户',
                platform: '对话系统'
              }
            };

            const itemId = await get().addItem(newItem);

            // 自动提取关键词并添加为标签
            if (itemId && conversationMessage.content) {
              setTimeout(async () => {
                try {
                  const keywords = await inspirationAIService.extractKeywords(
                    conversationMessage.content,
                    3
                  );
                  if (keywords.length > 0) {
                    const item = get().items.find(i => i.id === itemId);
                    if (item) {
                      await get().updateItem(itemId, {
                        tags: [...new Set([...item.tags, ...keywords])]
                      });
                      await get().loadTags();
                    }
                  }
                } catch (err) {
                  console.warn('自动提取关键词失败:', err);
                }
              }, 500);
            }

            message.success('已添加到灵感库');
            return itemId;
          } catch (error) {
            console.error('从对话添加失败:', error);
            message.error('添加失败');
            throw error;
          }
        },

        /**
         * 快速记录笔记
         */
        addQuickNote: async (content: string, tags: string[] = []) => {
          try {
            if (!content || !content.trim()) {
              message.warning('内容不能为空');
              throw new Error('Content is empty');
            }

            const newItem: Omit<InspirationItem, 'id' | 'createdAt' | 'updatedAt'> = {
              title: `快速笔记 - ${new Date().toLocaleString()}`,
              content: content.trim(),
              type: 'note',
              tags: ['快速笔记', ...tags],
              source: {
                url: '',
                title: '快速记录',
                author: '我',
                platform: '灵感库'
              }
            };

            const itemId = await get().addItem(newItem);
            message.success('笔记已保存');
            return itemId;
          } catch (error) {
            console.error('保存笔记失败:', error);
            message.error('保存失败');
            throw error;
          }
        },

        reset: () => set(initialState),
      }),
      {
        name: 'inspiration-storage',
        partialize: (state) => ({
          items: state.items,
        }),
      }
    ),
    { name: 'InspirationStore' }
  )
);
